<?php
/**
 * Created by PhpStorm.
 *
 * Author : Traveler.
 * Time   : 2019/12/16 14:56
 * Company: Inner Mongolia Zhengzhi Network Technology Co., Ltd
 */

namespace app\admin\controller;


use app\admin\BaseController;
use app\admin\middleware\Auth;
use app\admin\middleware\Login;
use app\admin\model\Config as ConfigModel;
use think\facade\View;

class Config extends BaseController
{
    /**
     * 控制器中间件
     * @var array
     */
    protected $middleware = [
        Auth::class => ['only' => ['save']],
        Login::class,
    ];

    /**
     * 渲染页面：参数配置
     * @return string
     */
    public function index()
    {
        // 获取系统配置
        $config = ConfigModel::getAllConfig();

        return View::assign('config', $config)->fetch();
    }

    /**
     * 保存配置
     * @return \think\response\Json
     */
    public function save()
    {
        $data = $this->request->post();
        if (empty($data) || !is_array($data)) {
            return $this->error('数据异常');
        }

        foreach ($data as $name => $value) {
            if (isset($data['default_password']) && strlen($data['default_password']) < PASSWORD_LENGTH_MIN) {
                return $this->error('密码长度不能小于' . PASSWORD_LENGTH_MIN . '位');
            }

            ConfigModel::update(['value' => $value], ['name' => $name]);
        }

        return $this->success('保存成功');
    }

}